package me.ezjs.framework.bridge;

import me.ezjs.framework.core.model.RootObject;
import me.ezjs.framework.util.JSONUtil;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.util.Date;

/**
 * Created by zero-mac on 16/3/10.
 */
@MappedSuperclass
public abstract class BaseObject extends RootObject {

    public BaseObject() {
        this.isUsing = 1;
        this.setModified();
    }

    public void setModified() {
        this.setModifyTime(new Date());
    }

    /**
     * 主键
     */
    protected String id;

    /**
     * 创建时间
     */
    protected Date createTime;
    protected Date modifyTime;

    private int isUsing; // 逻辑删除键,'是否在用',1启用中,0禁用中,-1逻辑删除了.

    @Override
    @Id
    @GenericGenerator(name = "idGenerator", strategy = "uuid")
    @GeneratedValue(generator = "idGenerator")
    @Column(length = 32)
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }

    @Temporal(TemporalType.TIMESTAMP)
    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Temporal(TemporalType.TIMESTAMP)
    public Date getModifyTime() {
        return modifyTime;
    }

    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
        if (id == null || id.length() == 0) {
            this.createTime = modifyTime;
        }
    }

    public int getIsUsing() {
        return isUsing;
    }

    public void setIsUsing(int isUsing) {
        this.isUsing = isUsing;
    }

    /**
     * 删除
     */
    public void removed() {
        this.isUsing = -1;
    }

    /**
     * 禁用
     */
    public void disabled() {
        this.isUsing = 0;
    }

    /**
     * 启用
     */
    public void enabled() {
        this.isUsing = 1;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (!(o instanceof BaseObject)) {
            return false;
        }

        if (id != null) {
            return this.id == ((BaseObject) o).id ? true : false;
        }
        return this.hashCode() == o.hashCode() ? true : false;
    }

    @Override
    public int hashCode() {
        if (id != null) {
            return id.hashCode();
        }
        return this.hashCode();
    }

    @Override
    public String toString() {
        return new JSONUtil(this).toString();
    }
}
